package com.hewanning.toy.play.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hewanning.toy.play.common.JsonResult;
import com.hewanning.toy.play.mapper.UserMapper;
import com.hewanning.toy.play.model.dto.LoginDto;
import com.hewanning.toy.play.model.entity.User;
import com.hewanning.toy.play.service.UserService;
import com.hewanning.toy.play.util.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户业务
 *
 * @author robin_he
 * @date 2020/1/6
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Object login(LoginDto loginDto) {
        User user = baseMapper.selectByName(loginDto.getLoginName());
        if (ObjectUtil.isNull(user)) {
            return JsonResult.fail("登录帐号不存在");
        }
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("loginName", loginDto.getLoginName());
        claims.put("userId", user.getId());
        claims.put("permissions", new ArrayList<>());
        if (loginDto.getPassword().equals(user.getPassword())) {
            JSONObject obj = jwtHelper.generateToken(claims);
            return JsonResult.success(obj);
        } else {
            return JsonResult.fail("登录密码错误");
        }
    }

    @Override
    public Object saveUser(User user) {
        User result = baseMapper.findByIdNotAndName(null, user.getName());
        if (ObjectUtil.isNotNull(result)) {
            return "false";
        }
        user.setId(null);
        boolean save = this.save(user);
        return save;
    }

    @Override
    public void logout(HttpServletRequest request) {
        jwtHelper.logout(request);
    }
}
